package club.beenest.framework.oss.service.impl;

import club.beenest.framework.oss.service.IFileStrategyClient;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;


public class TencentFileClient implements IFileStrategyClient {

    private String bucket;

    private final COSClient cosClient;

    public TencentFileClient(COSClient cosClient, String bucket) {
        this.cosClient = cosClient;
        this.bucket = bucket;
    }

    @Override
    public String upLoadFile(MultipartFile file, String fileName) {
        String eTag="";
        try {
            InputStream inputStream = file.getInputStream();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, inputStream, objectMetadata);
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //这里需要返回一个url地址给前端，如果你不需要可以不设置这个返回值
            eTag = putObjectResult.getETag();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return eTag;
    }

    @Override
    public byte[] downloadFile(String fileName) throws IOException {
        // 获取下载输入流
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, fileName);
        COSObject cosObject = cosClient.getObject(getObjectRequest);
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();
        return cosObjectInput.readAllBytes();
    }
}
